'''
Created on Feb 14, 2014

@author: yfrank
'''

import time

import CodingUtils.GeneralUtils as GeneralUtils

import Transport.ConnectionsThread as ConnectionsThread

import Simulation.SimulationPeer as SimulationPeer

import Transport.PeerTable as PeerTable

import Transport.IOHandler as IOHandler

import Transport.Channel as Channel

#from threading  import Lock as Lock

import os


class Server(object):
    '''
    classdocs
    '''
    sleep_interval = 1

    def __init__(self,host,port):

        self.host = host
        #self.lock = Lock()
        self.port = port #server listens on this port
        self.peer_table = PeerTable.PeerTable()
        self.iohandler = IOHandler.IOHandler(self.peer_table)
        self.connThread = ConnectionsThread.ConnectionsThread(self)

    def start(self):
        if self.connThread.init():
            self.connThread.start()
            self.iohandler.start()


    def stop(self):
        self.connThread.stop()
        self.iohandler.stop()


    def accept_peer(self,soc,addr):
        #self.lock.acquire()
        peer = self.get_peer(addr)
        channel = Channel.Channel(self.host,soc,addr)
        port = str(addr[1])
        dirname = os.getcwd()+'\\'+port
        while not  GeneralUtils.ensure_dir(port):
            time.sleep(Server.sleep_interval)
        if not peer:
            peer = SimulationPeer.SimulationPeer(channel,dirname)
            self.peer_table.add_peer(peer,addr)
        elif peer.isClosed():
            peer.reconnect(channel)
        #self.lock.release()


    def get_peer(self,addr):
        return self.peer_table.get_peer(addr)





if __name__ == '__main__':

    localhost = "127.0.0.1"
    server = Server(localhost,9221)

    server.start()
    #server.stop()
